from flask import Blueprint, request, jsonify
from app.models import db
from app.models.work_order import WorkOrder, WorkOrderField, WorkOrderFieldValue
from app.models.process_record import ProcessRecord
from app.models.material import Material, MaterialUsage
from app.utils.auth import require_permission, get_current_user
from datetime import datetime
import json
import traceback

def parse_datetime(date_str):
    """解析多种格式的日期时间字符串"""
    if not date_str:
        return None
    
    try:
        # 尝试ISO格式 (YYYY-MM-DDTHH:MM:SS)
        if 'T' in date_str:
            return datetime.fromisoformat(date_str.replace('Z', '+00:00'))
        else:
            # 尝试标准格式 (YYYY-MM-DD HH:MM:SS)
            return datetime.strptime(date_str, '%Y-%m-%d %H:%M:%S')
    except ValueError:
        # 如果都失败，尝试只有日期的格式 (YYYY-MM-DD)
        try:
            return datetime.strptime(date_str, '%Y-%m-%d')
        except ValueError:
            raise ValueError(f'无效的日期格式: {date_str}')

work_orders_bp = Blueprint('work_orders', __name__)

@work_orders_bp.route('', methods=['GET'])
@require_permission('work_order.view', 'work_order.view_all')
def get_work_orders():
    """获取工单列表"""
    try:
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 10, type=int)
        search = request.args.get('search', '')
        status = request.args.get('status')
        if status == '':
            status = None
        priority = request.args.get('priority')
        if priority == '':
            priority = None
        assignee_id = request.args.get('assignee_id', type=int)
        group_id = request.args.get('group_id', type=int)
        area_filter = request.args.get('area_filter', 'true').lower() == 'true'
        
        show_all = request.args.get('show_all', 'false').lower() == 'true'
        current_user = get_current_user()
        query = WorkOrder.query

        # 根据用户角色和 show_all 参数过滤数据
        if not (show_all and current_user.role in ['admin', 'superuser']):
            # 当状态为“未分配”时，所有用户都能看到
            if status == '未分配':
                pass
            elif current_user.role == 'user':
                # 普通用户只能看到自己创建的或分配给自己的工单
                user_filters = [
                    WorkOrder.creator_id == current_user.id,
                    WorkOrder.assignee_id == current_user.id
                ]
                
                # 如果启用区域过滤，还可以看到同区域的工单
                if area_filter:
                    user_area_ids = [area.id for area in current_user.areas.all()]
                    if current_user.area_id:
                        user_area_ids.append(current_user.area_id)
                    if user_area_ids:
                        user_filters.append(WorkOrder.area_id.in_(user_area_ids))
                
                query = query.filter(db.or_(*user_filters))
            elif current_user.role == 'manager':
                # 经理可以看到自己组的工单和自己区域的工单
                manager_filters = []
                
                # 组权限
                if current_user.group_id:
                    manager_filters.append(WorkOrder.group_id == current_user.group_id)
                    manager_filters.append(WorkOrder.group_id.is_(None))  # 包含未分组的工单
                
                # 区域权限
                if area_filter:
                    user_area_ids = [area.id for area in current_user.areas.all()]
                    if current_user.area_id:
                        user_area_ids.append(current_user.area_id)
                    if user_area_ids:
                        manager_filters.append(WorkOrder.area_id.in_(user_area_ids))
                
                if manager_filters:
                    query = query.filter(db.or_(*manager_filters))
        
        if search:
            query = query.filter(
                db.or_(
                    WorkOrder.order_number.contains(search),
                    WorkOrder.title.contains(search),
                    WorkOrder.description.contains(search)
                )
            )
        
        if status:
            # 支持多个状态值，用逗号分隔
            if ',' in status:
                status_list = [s.strip() for s in status.split(',')]
                query = query.filter(WorkOrder.status.in_(status_list))
            else:
                query = query.filter_by(status=status)
        
        if priority:
            query = query.filter_by(priority=priority)
        
        if assignee_id:
            query = query.filter_by(assignee_id=assignee_id)
        
        if group_id:
            query = query.filter_by(group_id=group_id)
        
        # 处理自定义字段过滤参数
        custom_fields = {}
        for key, value in request.args.items():
            if key.startswith('customFields[') and value:
                # 解析字段名
                field_name = key[len('customFields['):-1]
                custom_fields[field_name] = value
        
        for field_name, field_value in custom_fields.items():
            query = query.join(WorkOrder.field_values).filter(
                WorkOrderFieldValue.field.has(name=field_name),
                WorkOrderFieldValue.value == field_value
            )
        
        query = query.order_by(WorkOrder.created_at.desc())
        
        pagination = query.paginate(
            page=page, per_page=per_page, error_out=False
        )
        
        return jsonify({
            'work_orders': [order.to_dict() for order in pagination.items],
            'total': pagination.total,
            'pages': pagination.pages,
            'current_page': page
        }), 200
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@work_orders_bp.route('/materials/<int:usage_id>', methods=['DELETE'])
@require_permission('work_order.edit')
def delete_material_usage(usage_id):
    """删除材料使用记录"""
    try:
        current_user = get_current_user()
        usage = MaterialUsage.query.get_or_404(usage_id)
        work_order = usage.work_order
        material = usage.material

        # 权限检查 - 接单时允许用户更新未分配的工单
        if current_user.role == 'user':
            # 如果是接单操作（设置assignee_id为当前用户），允许更新未分配的工单
            is_accepting_order = (
                'assignee_id' in data and 
                data['assignee_id'] == current_user.id and 
                work_order.assignee_id is None
            )
            
            # 检查是否有权限：创建者、分配者、或者是接单操作
            if not (work_order.creator_id == current_user.id or 
                   work_order.assignee_id == current_user.id or 
                   is_accepting_order):
                return jsonify({'error': '权限不足'}), 403
        elif current_user.role == 'manager':
            if current_user.group_id and work_order.group_id != current_user.group_id:
                return jsonify({'error': '权限不足'}), 403

        # 归还库存
        material.stock_quantity += usage.quantity

        db.session.delete(usage)
        db.session.commit()

        return jsonify({'message': '删除成功'}), 200

    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500
@work_orders_bp.route('/materials/batch', methods=['POST'])
@require_permission('work_order.edit')
def add_multiple_material_usage():
    """批量添加材料使用记录"""
    try:
        data = request.get_json()
        current_user = get_current_user()

        if not isinstance(data, list):
            return jsonify({'error': '请求数据必须是列表格式'}), 400

        new_usages = []
        for item in data:
            work_order_id = item.get('work_order_id')
            material_id = item.get('material_id')
            quantity = item.get('quantity')

            if not all([work_order_id, material_id, quantity]):
                return jsonify({'error': '缺少必要参数'}), 400

            work_order = WorkOrder.query.get_or_404(work_order_id)
            material = Material.query.get_or_404(material_id)

            # 权限检查
            if current_user.role == 'user':
                if work_order.creator_id != current_user.id and work_order.assignee_id != current_user.id:
                    return jsonify({'error': f'工单 {work_order_id} 权限不足'}), 403
            elif current_user.role == 'manager':
                if current_user.group_id and work_order.group_id != current_user.group_id:
                    return jsonify({'error': f'工单 {work_order_id} 权限不足'}), 403

            # 检查库存
            if material.stock_quantity < quantity:
                return jsonify({'error': f'材料 {material.name} 库存不足'}), 400

            # 更新库存
            material.stock_quantity -= quantity

            usage = MaterialUsage(
                work_order_id=work_order_id,
                material_id=material_id,
                quantity=quantity,
                user_id=current_user.id,
                notes=item.get('notes')
            )
            db.session.add(usage)
            new_usages.append(usage)

        db.session.commit()

        return jsonify({'message': '材料录入成功', 'usages': [u.to_dict() for u in new_usages]}), 201

    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500

# 处理记录管理
@work_orders_bp.route('/<int:order_id>/records', methods=['GET'])
@require_permission('work_order.view', 'work_order.edit')
def get_process_records(order_id):
    """获取工单处理记录列表"""
    try:
        current_user = get_current_user()
        work_order = WorkOrder.query.get_or_404(order_id)

        # 权限检查 - 接单时允许用户更新未分配的工单
        if current_user.role == 'user':
            # 如果是接单操作（设置assignee_id为当前用户），允许更新未分配的工单
            is_accepting_order = (
                'assignee_id' in data and 
                data['assignee_id'] == current_user.id and 
                work_order.assignee_id is None
            )
            
            # 检查是否有权限：创建者、分配者、或者是接单操作
            if not (work_order.creator_id == current_user.id or 
                   work_order.assignee_id == current_user.id or 
                   is_accepting_order):
                return jsonify({'error': '权限不足'}), 403
        elif current_user.role == 'manager':
            if current_user.group_id and work_order.group_id != current_user.group_id:
                return jsonify({'error': '权限不足'}), 403

        records = ProcessRecord.query.filter_by(work_order_id=order_id).order_by(ProcessRecord.created_at.desc()).all()

        return jsonify({
            'records': [record.to_dict() for record in records]
        }), 200

    except Exception as e:
        return jsonify({'error': str(e)}), 500

@work_orders_bp.route('/<int:order_id>/records', methods=['POST'])
@require_permission('work_order.edit')
def create_process_record(order_id):
    """创建工单处理记录"""
    try:
        current_user = get_current_user()
        work_order = WorkOrder.query.get_or_404(order_id)
        data = request.get_json()

        # 权限检查
        if current_user.role == 'user':
            if work_order.creator_id != current_user.id and work_order.assignee_id != current_user.id:
                return jsonify({'error': '权限不足'}), 403
        elif current_user.role == 'manager':
            if current_user.group_id and work_order.group_id != current_user.group_id:
                return jsonify({'error': '权限不足'}), 403

        if not data.get('description'):
            return jsonify({'error': '处理记录描述不能为空'}), 400

        record = ProcessRecord(
            work_order_id=order_id,
            action=data.get('action', '处理记录'),
            description=data['description'],
            operator_id=current_user.id
        )

        db.session.add(record)
        db.session.commit()

        return jsonify({'record': record.to_dict()}), 201

    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500

@work_orders_bp.route('/<int:order_id>/materials', methods=['GET'])
@require_permission('work_order.view', 'work_order.edit')
def get_work_order_materials(order_id):
    """获取工单已使用的材料列表"""
    try:
        current_user = get_current_user()
        work_order = WorkOrder.query.get_or_404(order_id)

        # 权限检查
        if current_user.role == 'user':
            # 允许接单操作：如果是将未分配的工单分配给自己
            is_taking_order = ('assignee_id' in data and 
                             data['assignee_id'] == current_user.id and 
                             work_order.assignee_id is None)
            
            # 允许用户更新自己创建的、分配给自己的工单，或者接单操作
            if (work_order.creator_id != current_user.id and 
                work_order.assignee_id != current_user.id and 
                not is_taking_order):
                return jsonify({'error': '权限不足'}), 403
        elif current_user.role == 'manager':
            if current_user.group_id and work_order.group_id != current_user.group_id:
                return jsonify({'error': '权限不足'}), 403

        usages = MaterialUsage.query.filter_by(work_order_id=order_id).all()

        return jsonify({
            'materials': [usage.to_dict() for usage in usages]
        }), 200

    except Exception as e:
        return jsonify({'error': str(e)}), 500

@work_orders_bp.route('', methods=['POST'])
@require_permission('work_order.create')
def create_work_order():
    """创建工单"""
    try:
        data = request.get_json()
        current_user = get_current_user()

        # 移除工单标题必填验证

        # 生成工单号
        from datetime import datetime
        order_number = f"WO{datetime.now().strftime('%Y%m%d%H%M%S')}"

        # 确保工单号唯一
        counter = 1
        base_number = order_number
        while WorkOrder.query.filter_by(order_number=order_number).first():
            order_number = f"{base_number}_{counter}"
            counter += 1

        work_order = WorkOrder(
            order_number=order_number,
            title=data.get('title', ''),  # 设为可选字段
            description=data.get('description', ''),  # 设为可选字段
            type=data.get('type', 'maintenance'),  # 设为可选字段
            priority=data.get('priority', 'medium'),
            status=data.get('status', 'pending'),
            location=data.get('location', ''),  # 设为可选字段
            notes=data.get('notes', ''),
            creator_id=current_user.id,
            assignee_id=data.get('assignee_id'),
            group_id=data.get('group_id'),
            area_id=data.get('area_id'),  # 区域字段
            scheduled_start=parse_datetime(data.get('scheduled_start')) if data.get('scheduled_start') else None,
            scheduled_end=parse_datetime(data.get('scheduled_end')) if data.get('scheduled_end') else None
        )

        db.session.add(work_order)
        db.session.flush()  # 获取工单ID

        # 处理自定义字段
        custom_fields = data.get('custom_fields', {})
        for field_name, field_value in custom_fields.items():
            field = WorkOrderField.query.filter_by(name=field_name, is_active=True).first()
            if field and field_value is not None:
                # 处理日期类型字段的格式转换
                if field.field_type == 'date' and isinstance(field_value, str):
                    try:
                        # 尝试解析ISO格式日期并转换为标准格式
                        if 'T' in field_value:
                            parsed_date = datetime.fromisoformat(field_value.replace('Z', '+00:00'))
                            field_value = parsed_date.strftime('%Y-%m-%d')
                        # 如果已经是标准格式，保持不变
                    except ValueError:
                        # 如果解析失败，保持原值
                        pass
                
                # 处理多选字段，将数组转换为JSON字符串
                if field.field_type == 'checkbox' and isinstance(field_value, list):
                    field_value = json.dumps(field_value)
                
                field_value_obj = WorkOrderFieldValue(
                    work_order_id=work_order.id,
                    field_id=field.id,
                    value=str(field_value)
                )
                db.session.add(field_value_obj)
            elif field and field_value is None:
                # 处理空值情况
                field_value_obj = WorkOrderFieldValue(
                    work_order_id=work_order.id,
                    field_id=field.id,
                    value=None
                )
                db.session.add(field_value_obj)

        db.session.commit()

        return jsonify({'work_order': work_order.to_dict()}), 201

    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500

@work_orders_bp.route('/<int:order_id>', methods=['GET'])
@require_permission('work_order.view', 'work_order.edit')
def get_work_order(order_id):
    """获取工单详情"""
    try:
        current_user = get_current_user()
        work_order = WorkOrder.query.get_or_404(order_id)

        # 权限检查
        if current_user.role == 'user':
            # 允许接单操作：如果是将未分配的工单分配给自己
            is_taking_order = ('assignee_id' in data and 
                             data['assignee_id'] == current_user.id and 
                             work_order.assignee_id is None)
            
            # 允许用户更新自己创建的、分配给自己的工单，或者接单操作
            if (work_order.creator_id != current_user.id and 
                work_order.assignee_id != current_user.id and 
                not is_taking_order):
                return jsonify({'error': '权限不足'}), 403
        elif current_user.role == 'manager':
            if current_user.group_id and work_order.group_id != current_user.group_id:
                return jsonify({'error': '权限不足'}), 403

        return jsonify({'work_order': work_order.to_dict(include_custom_fields=True)}), 200

    except Exception as e:
        return jsonify({'error': str(e)}), 500

@work_orders_bp.route('/<int:order_id>', methods=['PUT'])
@require_permission('work_order.edit')
def update_work_order(order_id):
    """更新工单"""
    try:
        current_user = get_current_user()
        work_order = WorkOrder.query.get_or_404(order_id)
        data = request.get_json()

        # 权限检查
        if current_user.role == 'user':
            # 允许接单操作：如果是将未分配的工单分配给自己
            is_taking_order = ('assignee_id' in data and 
                             data['assignee_id'] == current_user.id and 
                             work_order.assignee_id is None)
            
            # 允许用户更新自己创建的、分配给自己的工单，或者接单操作
            if (work_order.creator_id != current_user.id and 
                work_order.assignee_id != current_user.id and 
                not is_taking_order):
                return jsonify({'error': '权限不足'}), 403
        elif current_user.role == 'manager':
            if current_user.group_id and work_order.group_id != current_user.group_id:
                return jsonify({'error': '权限不足'}), 403

        # 更新基本字段
        for field in ['title', 'description', 'type', 'priority', 'status', 'location', 'notes', 'assignee_id', 'group_id', 'area_id']:
            if field in data:
                setattr(work_order, field, data[field])

        # 更新时间字段
        for field in ['scheduled_start', 'scheduled_end', 'actual_start', 'actual_end']:
            if field in data and data[field]:
                # 处理多种日期格式
                date_str = data[field]
                try:
                    # 尝试ISO格式 (YYYY-MM-DDTHH:MM:SS)
                    if 'T' in date_str:
                        setattr(work_order, field, datetime.fromisoformat(date_str.replace('Z', '+00:00')))
                    else:
                        # 尝试标准格式 (YYYY-MM-DD HH:MM:SS)
                        setattr(work_order, field, datetime.strptime(date_str, '%Y-%m-%d %H:%M:%S'))
                except ValueError:
                    # 如果都失败，尝试只有日期的格式 (YYYY-MM-DD)
                    try:
                        setattr(work_order, field, datetime.strptime(date_str, '%Y-%m-%d'))
                    except ValueError:
                        return jsonify({'error': f'无效的日期格式: {date_str}'}), 400
            elif field in data and data[field] is None:
                setattr(work_order, field, None)

        # 更新自定义字段
        if 'custom_fields' in data:
            # 删除现有的自定义字段值
            WorkOrderFieldValue.query.filter_by(work_order_id=work_order.id).delete()

            # 添加新的自定义字段值
            custom_fields = data['custom_fields']
            for field_name, field_value in custom_fields.items():
                field = WorkOrderField.query.filter_by(name=field_name, is_active=True).first()
                if field and field_value is not None:
                    # 处理日期类型字段的格式转换
                    if field.field_type == 'date' and isinstance(field_value, str):
                        try:
                            # 尝试解析ISO格式日期并转换为标准格式
                            if 'T' in field_value:
                                parsed_date = datetime.fromisoformat(field_value.replace('Z', '+00:00'))
                                field_value = parsed_date.strftime('%Y-%m-%d')
                            # 如果已经是标准格式，保持不变
                        except ValueError:
                            # 如果解析失败，保持原值
                            pass
                    
                    # 处理多选字段，将数组转换为JSON字符串
                    if field.field_type == 'checkbox' and isinstance(field_value, list):
                        field_value = json.dumps(field_value)
                    
                    field_value_obj = WorkOrderFieldValue(
                        work_order_id=work_order.id,
                        field_id=field.id,
                        value=str(field_value)
                    )
                    db.session.add(field_value_obj)
                elif field and field_value is None:
                    # 处理空值情况
                    field_value_obj = WorkOrderFieldValue(
                        work_order_id=work_order.id,
                        field_id=field.id,
                        value=None
                    )
                    db.session.add(field_value_obj)

        db.session.commit()

        return jsonify({'work_order': work_order.to_dict()}), 200

    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500

@work_orders_bp.route('/<int:order_id>', methods=['DELETE'])
@require_permission('work_order.delete')
def delete_work_order(order_id):
    """删除工单"""
    try:
        work_order = WorkOrder.query.get_or_404(order_id)
        current_user = get_current_user()

        # 权限检查
        if current_user.role == 'manager':
            if current_user.group_id and work_order.group_id != current_user.group_id:
                return jsonify({'error': '权限不足'}), 403

        # 先删除相关的处理记录
        ProcessRecord.query.filter_by(work_order_id=order_id).delete()
        
        # 删除相关的自定义字段值
        WorkOrderFieldValue.query.filter_by(work_order_id=order_id).delete()
        
        # 最后删除工单
        db.session.delete(work_order)
        db.session.commit()

        return jsonify({'message': '工单删除成功'}), 200

    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500

# 自定义字段管理
@work_orders_bp.route('/fields', methods=['GET'])
@require_permission('work_order.view', 'work_order.edit')
def get_work_order_fields():
    """获取工单自定义字段列表"""
    try:
        fields = WorkOrderField.query.filter_by(is_active=True).order_by(WorkOrderField.sort_order).all()

        return jsonify({
            'fields': [field.to_dict() for field in fields]
        }), 200

    except Exception as e:
        return jsonify({'error': str(e)}), 500

@work_orders_bp.route('/fields', methods=['POST'])
@require_permission('work_order.field_manage')
def create_work_order_field():
    """创建工单自定义字段"""
    try:
        data = request.get_json()

        if not data.get('name'):
            return jsonify({'error': '字段名称不能为空'}), 400

        # 自动生成标签，如果未提供
        label = data.get('label') if data.get('label') else data['name']

        # 检查字段名是否已存在
        if WorkOrderField.query.filter_by(name=data['name']).first():
            return jsonify({'error': '字段名称已存在'}), 400

        field = WorkOrderField(
            name=data['name'],
            label=label,  # 使用生成的标签
            field_type=data.get('field_type', 'text'),
            options=json.dumps(data['options']) if data.get('options') else None,
            is_required=data.get('is_required', False),
            default_value=data.get('default_value'),
            placeholder=data.get('placeholder'),
            sort_order=data.get('sort_order', 0)
        )

        db.session.add(field)
        db.session.commit()

        return jsonify({'field': field.to_dict()}), 201

    except Exception as e:
        db.session.rollback()
        error_message = str(e) + "\n" + traceback.format_exc()
        print(f"Error creating work order field: {error_message}")
        return jsonify({'error': error_message}), 500

@work_orders_bp.route('/fields/<int:field_id>', methods=['PUT'])
@require_permission('work_order.field_manage')
def update_work_order_field(field_id):
    """更新工单自定义字段"""
    try:
        field = WorkOrderField.query.get_or_404(field_id)
        data = request.get_json()

        if not data:
            return jsonify({'error': '未收到请求数据'}), 400

        # 检查字段名是否已被其他字段使用
        if 'name' in data and data['name'] != field.name:
            if WorkOrderField.query.filter_by(name=data['name']).first():
                return jsonify({'error': '字段名称已存在'}), 400

        # 更新字段
        updatable_fields = ['name', 'field_type', 'is_required', 'default_value', 'placeholder', 'sort_order', 'is_active']
        for attr in updatable_fields:
            if attr in data:
                setattr(field, attr, data[attr])

        # 处理label字段
        if 'label' in data:
            field.label = data['label']
        else:
            # 如果没有提供label，保持原值或使用name
            field.label = field.name if field.name is not None else data.get('name', field.label)

        # 确保label不为空
        if field.label is None or field.label == '':
            field.label = field.name if field.name is not None else '未命名字段'

        if 'options' in data:
            # 特别处理options字段：空数组转换为None
            if data['options'] is None or (isinstance(data['options'], list) and len(data['options']) == 0):
                field.options = None
            else:
                field.options = json.dumps(data['options'])

        db.session.commit()

        return jsonify({'field': field.to_dict()}), 200

    except Exception as e:
        db.session.rollback()
        # 记录详细错误信息
        print(f"Error updating work order field: {str(e)}")
        return jsonify({'error': str(e)}), 500

@work_orders_bp.route('/fields/<int:field_id>', methods=['DELETE'])
@require_permission('work_order.field_manage')
def delete_work_order_field(field_id):
    """删除工单自定义字段"""
    try:
        field = WorkOrderField.query.get_or_404(field_id)

        # 删除相关的字段值
        WorkOrderFieldValue.query.filter_by(field_id=field.id).delete()

        db.session.delete(field)
        db.session.commit()

        return jsonify({'message': '字段删除成功'}), 200

    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500

@work_orders_bp.route('/stats', methods=['GET'])
@require_permission('work_order.view', 'work_order.view_all')
def get_work_order_stats():
    """获取工单统计数据"""
    try:
        current_user = get_current_user()
        query = WorkOrder.query

        # 根据用户角色过滤数据
        if current_user.role == 'user':
            # 普通用户只能看到自己创建的或分配给自己的工单
            query = query.filter(
                db.or_(
                    WorkOrder.creator_id == current_user.id,
                    WorkOrder.assignee_id == current_user.id
                )
            )
        elif current_user.role == 'manager':
            # 管理员可以看到自己组的工单
            if current_user.group_id:
                query = query.filter(WorkOrder.group_id == current_user.group_id)

        # 统计各状态的工单数量
        total = query.count()
        pending = query.filter_by(status='pending').count()
        assigned = query.filter_by(status='assigned').count()
        in_progress = query.filter_by(status='in_progress').count()
        completed = query.filter_by(status='completed').count()
        cancelled = query.filter_by(status='cancelled').count()

        return jsonify({
            'total': total,
            'pending': pending,
            'assigned': assigned,
            'in_progress': in_progress,
            'completed': completed,
            'cancelled': cancelled
        }), 200

    except Exception as e:
        return jsonify({'error': str(e)}), 500

@work_orders_bp.route('/reports', methods=['GET'])
@require_permission('work_order.view', 'work_order.view_all')
def get_work_order_reports():
    """获取工单报表数据"""
    try:
        from datetime import datetime, timedelta
        from sqlalchemy import func, extract
        
        current_user = get_current_user()
        
        # 获取查询参数
        start_date = request.args.get('start_date')
        end_date = request.args.get('end_date')
        dimension = request.args.get('dimension', 'day')  # day, week, month
        
        # 设置默认时间范围（最近30天）
        if not start_date:
            start_date = (datetime.now() - timedelta(days=30)).strftime('%Y-%m-%d')
        if not end_date:
            end_date = datetime.now().strftime('%Y-%m-%d')
            
        # 转换为datetime对象
        start_dt = datetime.strptime(start_date, '%Y-%m-%d')
        end_dt = datetime.strptime(end_date, '%Y-%m-%d') + timedelta(days=1)
        
        # 基础查询
        query = WorkOrder.query.filter(
            WorkOrder.created_at >= start_dt,
            WorkOrder.created_at < end_dt
        )
        
        # 根据用户角色过滤数据
        if current_user.role == 'user':
            query = query.filter(
                db.or_(
                    WorkOrder.creator_id == current_user.id,
                    WorkOrder.assignee_id == current_user.id
                )
            )
        elif current_user.role == 'manager':
            if current_user.group_id:
                query = query.filter(WorkOrder.group_id == current_user.group_id)
        
        # 统计概览数据
        total_orders = query.count()
        completed_orders = query.filter_by(status='completed').count()
        pending_orders = query.filter_by(status='pending').count()
        processing_orders = query.filter(
            WorkOrder.status.in_(['assigned', 'in_progress'])
        ).count()
        
        completion_rate = round((completed_orders / total_orders * 100) if total_orders > 0 else 0, 1)
        
        # 状态分布统计
        status_stats = {
            'pending': query.filter_by(status='pending').count(),
            'assigned': query.filter_by(status='assigned').count(),
            'in_progress': query.filter_by(status='in_progress').count(),
            'completed': query.filter_by(status='completed').count(),
            'cancelled': query.filter_by(status='cancelled').count()
        }
        
        # 优先级分布统计
        priority_stats = {
            'low': query.filter_by(priority='low').count(),
            'medium': query.filter_by(priority='medium').count(),
            'high': query.filter_by(priority='high').count(),
            'urgent': query.filter_by(priority='urgent').count()
        }
        
        # 按时间维度统计趋势数据
        trend_data = []
        detail_data = []
        
        if dimension == 'day':
            # 按天统计
            current_date = start_dt
            while current_date < end_dt:
                next_date = current_date + timedelta(days=1)
                day_query = query.filter(
                    WorkOrder.created_at >= current_date,
                    WorkOrder.created_at < next_date
                )
                
                day_total = day_query.count()
                day_completed = day_query.filter_by(status='completed').count()
                day_pending = day_query.filter_by(status='pending').count()
                day_processing = day_query.filter(
                    WorkOrder.status.in_(['assigned', 'in_progress'])
                ).count()
                day_cancelled = day_query.filter_by(status='cancelled').count()
                
                day_completion_rate = round((day_completed / day_total * 100) if day_total > 0 else 0, 1)
                
                trend_data.append({
                    'date': current_date.strftime('%Y-%m-%d'),
                    'total': day_total,
                    'completed': day_completed
                })
                
                detail_data.append({
                    'date': current_date.strftime('%Y-%m-%d'),
                    'total': day_total,
                    'pending': day_pending,
                    'processing': day_processing,
                    'completed': day_completed,
                    'cancelled': day_cancelled,
                    'completion_rate': day_completion_rate,
                    'avg_duration': '待计算'  # 这里可以后续添加平均处理时长计算
                })
                
                current_date = next_date
        
        return jsonify({
            'stats': {
                'total': total_orders,
                'completed': completed_orders,
                'pending': pending_orders,
                'processing': processing_orders,
                'completionRate': completion_rate
            },
            'status_distribution': status_stats,
            'priority_distribution': priority_stats,
            'trend_data': trend_data,
            'detail_data': detail_data
        }), 200
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500
